<?php
/**
 * Created by PhpStorm.
 * User: Merdan
 * Date: 2017/4/14
 * Time: 12:56
 */

namespace App\Http\Controllers;


use App\Exceptions\BaseException;
use App\Http\Requests\SkuRequest;
use App\Services\Sku;
use Illuminate\Http\Request;

class SkuController extends Controller
{
    protected $skuService;

    function __construct()
    {
        parent::__construct();
        $this->skuService = new Sku();
    }

    /**
     * 存库列表
     *
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        try{
            $limit = intval($request->get('count',20));
            $filter = $request->get('filter', []);
            if(!isset($filter['name'])){
                $filter['name'] = null;
            }
            if(!isset($filter['category_id'])){
                $filter['category_id'] = null;
            }
            $sku = $this->skuService->getList($limit, $filter['name'], $filter['category_id']);
            return $this->success('',$sku);
        }catch(BaseException $e){
            return $this->fail($e->getMessage());
        }catch (\Exception $e){
            \Log::error($e);
            return $this->fail('发生意外错误, 请稍后重试!');
        }
    }

    /**
     * 获取单个存库信息
     *
     * @param $id
     * @return array
     */
    public function show($id)
    {
        try{
            $id = intval($id);
            $sku = $this->skuService->show($id);
            return $this->success('', $sku);
        }catch(BaseException $e){
            return $this->fail($e->getMessage());
        }catch (\Exception $e){
            \Log::error($e);
            return $this->fail('发生意外错误, 请稍后重试!');
        }
    }

    /**
     * 新增存库
     *
     * @param SkuRequest $request
     * @return array
     */
    public function store(SkuRequest $request)
    {
        try{
            $user_id = $this->user->id;
            $canteen_id = $this->user->canteen->id;
            $quantity = intval($request->get('quantity', 0));
            $price = intval($request->get('price', 0));
            $product_id = intval($request->get('product_id', 0));
            $type = 0;
            $this->skuService->create(compact('quantity', 'price', 'type', 'product_id', 'user_id', 'canteen_id'));
            return $this->success('新增存库成功!');

        }catch(BaseException $e){
            return $this->fail($e->getMessage());
        }catch (\Exception $e){
            \Log::error($e);
            return $this->fail('发生意外错误, 请稍后重试!');
        }
    }
}